import aioredis
from sanic import Sanic
from uvloop.loop import Loop


async def setup_redis(app: Sanic, loop: Loop) -> None:
    print("before_server_start setup_redis")
    app.ctx.redis = await aioredis.from_url(
        url=app.config.REDIS_DSN,
        decode_responses=True
    )
    app.ctx.redis_bytes = await aioredis.from_url(
        url=app.config.REDIS_DSN
    )


async def close_redis(app: Sanic, loop: Loop) -> None:
    print("after_server_stop close_redis")
    await app.ctx.redis.close()
    await app.ctx.redis_bytes.close()


def configure_redis_listeners(app: Sanic) -> None:
    app.register_listener(setup_redis, "before_server_start")
    app.register_listener(close_redis, "after_server_stop")
